// 登录页面 JavaScript

// 全局变量
let currentAuthTab = 'login';
let isLoading = false;

// DOM 元素
const authTabs = document.querySelectorAll('.auth-tab');
const authForms = document.querySelectorAll('.auth-form');
const loginForm = document.getElementById('login-form');
const registerForm = document.getElementById('register-form');
const welcomeOverlay = document.getElementById('welcome-overlay');
const toastContainer = document.getElementById('toast-container');

// 模拟用户数据
const mockUsers = [
    {
        email: 'demo@tracker.com',
        password: '123456',
        name: '演示用户'
    },
    {
        email: 'test@example.com',
        password: 'password',
        name: '测试用户'
    }
];

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    console.log('🚀 登录页面初始化中...');
    
    initializeLogin();
    setupEventListeners();
    setupFormValidation();
    updateStatusBar();
    animatePageLoad();
    
    console.log('✅ 登录页面加载完成');
});

// 初始化登录功能
function initializeLogin() {
    // 检查记住我的状态
    const rememberedEmail = localStorage.getItem('rememberedEmail');
    if (rememberedEmail) {
        const emailInput = document.getElementById('login-email');
        const rememberCheckbox = document.getElementById('remember');
        if (emailInput && rememberCheckbox) {
            emailInput.value = rememberedEmail;
            rememberCheckbox.checked = true;
        }
    }
    
    // 检查是否已登录
    const isLoggedIn = localStorage.getItem('isLoggedIn');
    if (isLoggedIn === 'true') {
        redirectToMain();
    }
}

// 设置事件监听器
function setupEventListeners() {
    // 标签切换
    authTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            const tabType = this.dataset.tab;
            switchAuthTab(tabType);
            hapticFeedback();
        });
    });
    
    // 表单提交
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
    }
    
    if (registerForm) {
        registerForm.addEventListener('submit', handleRegister);
    }
    
    // 密码显示切换
    document.querySelectorAll('.password-toggle').forEach(btn => {
        btn.addEventListener('click', function() {
            togglePasswordVisibility(this);
            hapticFeedback();
        });
    });
    
    // 第三方登录
    document.querySelectorAll('.social-button').forEach(btn => {
        btn.addEventListener('click', function() {
            const platform = this.classList[1]; // wechat, qq, apple
            handleSocialLogin(platform);
        });
    });
    
    // 游客体验
    const quickExperienceBtn = document.querySelector('.quick-experience');
    if (quickExperienceBtn) {
        quickExperienceBtn.addEventListener('click', function() {
            handleGuestLogin();
        });
    }
    
    // 忘记密码
    const forgotPasswordLink = document.querySelector('.forgot-password');
    if (forgotPasswordLink) {
        forgotPasswordLink.addEventListener('click', function(e) {
            e.preventDefault();
            handleForgotPassword();
        });
    }
    
    // 输入框焦点动画
    document.querySelectorAll('input').forEach(input => {
        input.addEventListener('focus', function() {
            this.closest('.input-wrapper').classList.add('focused');
        });
        
        input.addEventListener('blur', function() {
            if (!this.value) {
                this.closest('.input-wrapper').classList.remove('focused');
            }
        });
    });
}

// 设置表单验证
function setupFormValidation() {
    // 实时验证
    document.querySelectorAll('input').forEach(input => {
        input.addEventListener('input', function() {
            validateField(this);
        });
        
        input.addEventListener('blur', function() {
            validateField(this);
        });
    });
    
    // 注册时密码确认验证
    const confirmPasswordInput = document.getElementById('register-confirm-password');
    if (confirmPasswordInput) {
        confirmPasswordInput.addEventListener('input', function() {
            validatePasswordMatch();
        });
    }
}

// 更新状态栏时间
function updateStatusBar() {
    const timeElement = document.querySelector('.time');
    if (timeElement) {
        const updateTime = () => {
            const now = new Date();
            const timeString = now.toLocaleTimeString('en-US', {
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
            });
            timeElement.textContent = timeString;
        };
        
        updateTime();
        setInterval(updateTime, 1000);
    }
}

// 页面加载动画
function animatePageLoad() {
    const elements = document.querySelectorAll('.app-logo, .app-title, .login-form-section, .social-login');
    
    elements.forEach((element, index) => {
        element.style.opacity = '0';
        element.style.transform = 'translateY(30px)';
        
        setTimeout(() => {
            element.style.transition = 'all 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55)';
            element.style.opacity = '1';
            element.style.transform = 'translateY(0)';
        }, index * 200);
    });
}

// 切换认证标签
function switchAuthTab(tabType) {
    if (tabType === currentAuthTab) return;
    
    currentAuthTab = tabType;
    
    // 更新标签状态
    authTabs.forEach(tab => {
        tab.classList.toggle('active', tab.dataset.tab === tabType);
    });
    
    // 切换表单
    authForms.forEach(form => {
        if (form.id.includes(tabType)) {
            form.classList.remove('hidden');
            form.style.animation = 'slideInRight 0.3s ease';
        } else {
            form.classList.add('hidden');
        }
    });
}

// 处理登录
async function handleLogin(e) {
    e.preventDefault();
    
    if (isLoading) return;
    
    const formData = new FormData(e.target);
    const email = formData.get('email') || document.getElementById('login-email').value;
    const password = formData.get('password') || document.getElementById('login-password').value;
    const remember = document.getElementById('remember').checked;
    
    // 表单验证
    if (!validateLoginForm(email, password)) {
        return;
    }
    
    setButtonLoading(true);
    hapticFeedback();
    
    try {
        // 模拟登录API调用
        const loginResult = await simulateLogin(email, password);
        
        if (loginResult.success) {
            // 保存登录状态
            localStorage.setItem('isLoggedIn', 'true');
            localStorage.setItem('currentUser', JSON.stringify(loginResult.user));
            
            if (remember) {
                localStorage.setItem('rememberedEmail', email);
            } else {
                localStorage.removeItem('rememberedEmail');
            }
            
            showToast('登录成功！正在跳转...', 'success');
            
            // 显示欢迎动画
            showWelcomeAnimation(() => {
                redirectToMain();
            });
            
        } else {
            showToast(loginResult.message || '登录失败，请重试', 'error');
            hapticFeedback('error');
        }
        
    } catch (error) {
        console.error('登录错误:', error);
        showToast('网络错误，请检查连接', 'error');
        hapticFeedback('error');
    } finally {
        setButtonLoading(false);
    }
}

// 处理注册
async function handleRegister(e) {
    e.preventDefault();
    
    if (isLoading) return;
    
    const formData = new FormData(e.target);
    const name = document.getElementById('register-name').value;
    const email = document.getElementById('register-email').value;
    const password = document.getElementById('register-password').value;
    const confirmPassword = document.getElementById('register-confirm-password').value;
    const agreeTerms = document.getElementById('agree-terms').checked;
    
    // 表单验证
    if (!validateRegisterForm(name, email, password, confirmPassword, agreeTerms)) {
        return;
    }
    
    setButtonLoading(true);
    hapticFeedback();
    
    try {
        // 模拟注册API调用
        const registerResult = await simulateRegister(name, email, password);
        
        if (registerResult.success) {
            showToast('注册成功！请登录您的账号', 'success');
            
            // 切换到登录标签并填充邮箱
            switchAuthTab('login');
            document.getElementById('login-email').value = email;
            
        } else {
            showToast(registerResult.message || '注册失败，请重试', 'error');
            hapticFeedback('error');
        }
        
    } catch (error) {
        console.error('注册错误:', error);
        showToast('网络错误，请检查连接', 'error');
        hapticFeedback('error');
    } finally {
        setButtonLoading(false);
    }
}

// 处理第三方登录
function handleSocialLogin(platform) {
    hapticFeedback();
    
    const platformNames = {
        wechat: '微信',
        qq: 'QQ',
        apple: 'Apple ID'
    };
    
    showToast(`正在启动${platformNames[platform]}登录...`, 'info');
    
    // 模拟第三方登录流程
    setTimeout(() => {
        const success = Math.random() > 0.3; // 70% 成功率
        
        if (success) {
            const mockUser = {
                name: `${platformNames[platform]}用户`,
                email: `${platform}@example.com`,
                avatar: `https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=100&h=100&fit=crop&crop=face`
            };
            
            localStorage.setItem('isLoggedIn', 'true');
            localStorage.setItem('currentUser', JSON.stringify(mockUser));
            
            showToast(`${platformNames[platform]}登录成功！`, 'success');
            
            showWelcomeAnimation(() => {
                redirectToMain();
            });
            
        } else {
            showToast(`${platformNames[platform]}登录失败，请重试`, 'error');
            hapticFeedback('error');
        }
    }, 1500);
}

// 处理游客登录
function handleGuestLogin() {
    hapticFeedback();
    
    const guestUser = {
        name: '游客用户',
        email: 'guest@tracker.com',
        isGuest: true
    };
    
    localStorage.setItem('isLoggedIn', 'true');
    localStorage.setItem('currentUser', JSON.stringify(guestUser));
    
    showToast('正在进入游客体验模式...', 'info');
    
    setTimeout(() => {
        redirectToMain();
    }, 1000);
}

// 处理忘记密码
function handleForgotPassword() {
    hapticFeedback();
    
    // 简单的忘记密码处理
    const email = document.getElementById('login-email').value;
    
    if (!email) {
        showToast('请先输入您的邮箱地址', 'info');
        document.getElementById('login-email').focus();
        return;
    }
    
    if (!isValidEmail(email)) {
        showToast('请输入有效的邮箱地址', 'error');
        return;
    }
    
    showToast('密码重置邮件已发送到您的邮箱', 'success');
}

// 表单验证函数
function validateLoginForm(email, password) {
    if (!email) {
        showToast('请输入邮箱地址', 'error');
        document.getElementById('login-email').focus();
        return false;
    }
    
    if (!isValidEmail(email)) {
        showToast('请输入有效的邮箱地址', 'error');
        document.getElementById('login-email').focus();
        return false;
    }
    
    if (!password) {
        showToast('请输入密码', 'error');
        document.getElementById('login-password').focus();
        return false;
    }
    
    if (password.length < 6) {
        showToast('密码长度不能少于6位', 'error');
        document.getElementById('login-password').focus();
        return false;
    }
    
    return true;
}

function validateRegisterForm(name, email, password, confirmPassword, agreeTerms) {
    if (!name || name.trim().length < 2) {
        showToast('用户名至少需要2个字符', 'error');
        document.getElementById('register-name').focus();
        return false;
    }
    
    if (!email || !isValidEmail(email)) {
        showToast('请输入有效的邮箱地址', 'error');
        document.getElementById('register-email').focus();
        return false;
    }
    
    if (!password || password.length < 6) {
        showToast('密码长度不能少于6位', 'error');
        document.getElementById('register-password').focus();
        return false;
    }
    
    if (password !== confirmPassword) {
        showToast('两次输入的密码不一致', 'error');
        document.getElementById('register-confirm-password').focus();
        return false;
    }
    
    if (!agreeTerms) {
        showToast('请阅读并同意用户协议', 'error');
        return false;
    }
    
    return true;
}

function validateField(input) {
    const value = input.value.trim();
    const type = input.type;
    const id = input.id;
    
    let isValid = true;
    let message = '';
    
    switch (type) {
        case 'email':
            isValid = !value || isValidEmail(value);
            message = '请输入有效的邮箱地址';
            break;
        case 'password':
            isValid = !value || value.length >= 6;
            message = '密码长度不能少于6位';
            break;
        default:
            if (id === 'register-name') {
                isValid = !value || value.length >= 2;
                message = '用户名至少需要2个字符';
            }
            break;
    }
    
    // 更新输入框样式
    const wrapper = input.closest('.input-wrapper');
    if (wrapper) {
        if (value && !isValid) {
            wrapper.classList.add('error');
        } else {
            wrapper.classList.remove('error');
        }
    }
    
    return isValid;
}

function validatePasswordMatch() {
    const password = document.getElementById('register-password').value;
    const confirmPassword = document.getElementById('register-confirm-password').value;
    const wrapper = document.getElementById('register-confirm-password').closest('.input-wrapper');
    
    if (confirmPassword && password !== confirmPassword) {
        wrapper.classList.add('error');
        return false;
    } else {
        wrapper.classList.remove('error');
        return true;
    }
}

// 工具函数
function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

function setButtonLoading(loading) {
    isLoading = loading;
    
    const currentForm = currentAuthTab === 'login' ? loginForm : registerForm;
    const button = currentForm.querySelector('.auth-button');
    
    if (loading) {
        button.classList.add('loading');
        button.disabled = true;
    } else {
        button.classList.remove('loading');
        button.disabled = false;
    }
}

// 切换密码可见性
function togglePasswordVisibility(button) {
    const input = button.previousElementSibling;
    const icon = button.querySelector('i');
    
    if (input.type === 'password') {
        input.type = 'text';
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    } else {
        input.type = 'password';
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
}

// 模拟登录API
async function simulateLogin(email, password) {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 1500));
    
    // 查找用户
    const user = mockUsers.find(u => u.email === email && u.password === password);
    
    if (user) {
        return {
            success: true,
            user: {
                name: user.name,
                email: user.email,
                avatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=100&h=100&fit=crop&crop=face'
            }
        };
    } else {
        return {
            success: false,
            message: '邮箱或密码错误'
        };
    }
}

// 模拟注册API
async function simulateRegister(name, email, password) {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    // 检查邮箱是否已存在
    const existingUser = mockUsers.find(u => u.email === email);
    
    if (existingUser) {
        return {
            success: false,
            message: '该邮箱已被注册'
        };
    }
    
    // 模拟添加新用户
    mockUsers.push({
        name,
        email,
        password
    });
    
    return {
        success: true,
        message: '注册成功'
    };
}

// 显示欢迎动画
function showWelcomeAnimation(callback) {
    welcomeOverlay.classList.add('active');
    
    // 模拟加载进度
    const progressFill = welcomeOverlay.querySelector('.progress-fill');
    const progressText = welcomeOverlay.querySelector('.progress-text');
    
    let progress = 0;
    const interval = setInterval(() => {
        progress += Math.random() * 20;
        if (progress > 100) progress = 100;
        
        progressFill.style.width = `${progress}%`;
        progressText.textContent = `${Math.round(progress)}%`;
        
        if (progress >= 100) {
            clearInterval(interval);
            setTimeout(() => {
                welcomeOverlay.classList.remove('active');
                callback();
            }, 500);
        }
    }, 200);
}

// 跳转到主应用
function redirectToMain() {
    // 这里可以跳转到主应用页面
    window.location.href = 'mobile-app.html';
}

// 显示Toast消息
function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.textContent = message;
    
    toastContainer.appendChild(toast);
    
    // 触发显示动画
    setTimeout(() => {
        toast.classList.add('show');
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            if (toastContainer.contains(toast)) {
                toastContainer.removeChild(toast);
            }
        }, 300);
    }, 3000);
}

// 触觉反馈
function hapticFeedback(type = 'light') {
    if ('vibrate' in navigator) {
        switch(type) {
            case 'light':
                navigator.vibrate(10);
                break;
            case 'success':
                navigator.vibrate([100, 30, 100]);
                break;
            case 'error':
                navigator.vibrate([200, 100, 200]);
                break;
        }
    }
}

// 添加一些额外的CSS动画
const additionalStyles = document.createElement('style');
additionalStyles.textContent = `
    .input-wrapper.error input {
        border-color: #ef4444 !important;
        box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1) !important;
    }
    
    .input-wrapper.error .input-icon {
        color: #ef4444 !important;
    }
    
    @keyframes slideInRight {
        from {
            opacity: 0;
            transform: translateX(30px);
        }
        to {
            opacity: 1;
            transform: translateX(0);
        }
    }
    
    /* 防止页面缩放 */
    input[type="password"],
    input[type="email"],
    input[type="text"] {
        font-size: 16px !important;
    }
`;
document.head.appendChild(additionalStyles);

// 防止页面滚动弹跳
document.addEventListener('touchstart', function(e) {
    if (e.touches.length > 1) {
        e.preventDefault();
    }
});

let lastTouchEnd = 0;
document.addEventListener('touchend', function(e) {
    const now = (new Date()).getTime();
    if (now - lastTouchEnd <= 300) {
        e.preventDefault();
    }
    lastTouchEnd = now;
}, false);

// 导出API
window.LoginApp = {
    switchAuthTab,
    showToast,
    hapticFeedback,
    redirectToMain
};

console.log('🎉 登录页面JavaScript加载完成！');
console.log('👤 测试账号：demo@tracker.com / 123456');
console.log('🎮 支持功能：表单验证、第三方登录、游客模式、触觉反馈');